<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// "Hackware Web Services Core" is released under the MIT License terms.

namespace Hawese\Core\Http\Controllers;

use Hawese\Core\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['login', 'emailToken']]);
    }

    public function whoami(Request $request)
    {
        return $request->user();
    }

    public function login(Request $request): User
    {
        // TODO: return a message if app('auth')->check() is true?

        $this->validate($request, [
            'username' => 'required',
            'password' => 'required'
        ]);

        return User::loginByPassword(
            $request->input('username'),
            $request->input('password'),
            $request->filled('remember')
        );
    }

    public function logout(Request $request)
    {
        return $request->user()->logout() ? 'true' : 'false';
    }

    public function emailToken(Request $request)
    {
        if ($request->has('origin_url')) {
            $origin_url = $request->input('origin_url');
        } else {
            $referer = parse_url($request->server->get('HTTP_REFERER'));
            $origin_url = strtr(
                '$scheme://$host$port',
                [
                    '$scheme' => $referer['scheme'],
                    '$host' => $referer['host'],
                    '$port' => $referer['port'] ? ':' . $referer['port'] : ''
                ]
            );
        }

        return User::emailToken($request->input('username'), $origin_url);
    }
}
